package com.ufox.utils;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class EmailUtil {


    /**
     *
     * @param myEmailAccount  发送方账户
     * @param myEmailPassword   秘钥
     * @param receiveMailAccount   接收方账户
     * @param title   邮件标题
     * @param body    邮件身体
     * @throws Exception
     */
	public static void sendEmail(String myEmailAccount,String myEmailPassword,
                                 String receiveMailAccount,String title,String body) throws Exception {

		String myEmailSMTPHost = "smtp.qq.com";
		
		//String myEmailAccount = "181186368@qq.com";
		//String myEmailPassword = "gtqmfptgzeoobihd";
		//String receiveMailAccount = "wanpeng1006@126.com";
		
		Properties props = new Properties();
	    props.setProperty("mail.transport.protocol", "smtp");  
	    props.setProperty("mail.smtp.host", myEmailSMTPHost);   
	    props.setProperty("mail.smtp.auth", "true");
	    final String smtpPort = "465";
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.socketFactory.port", smtpPort);
	    
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true); 
        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(myEmailAccount));

        //message.setRecipient(MimeMessage.RecipientType.CC,  new InternetAddress("1050213519@qq.com", "1050213519", "UTF-8"));
        //message.setRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(props.getProperty("username")));
        
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMailAccount));

        //String title = "bbbb";
        message.setSubject(title,"UTF-8");

        //String body = "22222";
        message.setContent(body,"text/html;charset=UTF-8");

        message.setSentDate(new Date());

        message.saveChanges();
		
        Transport transport = session.getTransport();
        
        transport.connect(myEmailAccount, myEmailPassword);

        transport.sendMessage(message, message.getAllRecipients());

        transport.close();
	}
}
